package com.chang.bootplus.controller.storage.local;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chang.bootplus.base.utils.ApiResponse;
import com.chang.bootplus.base.exception.BusException;
import com.chang.bootplus.entity.StuExecl;
import com.chang.bootplus.entity.Student;
import com.chang.bootplus.po.StudentForTimeStuIdPO;
import com.chang.bootplus.service.StuExeclService;
import com.chang.bootplus.service.StudentService;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author lcc
 * @create 2021-05-28
 * @注意 本内容仅限于dev414内部传阅，禁止外泄以及用于其他的商业目的
 */
@Service
public class LocalService {

    @Autowired
    StuExeclService stuExeclService;

    @Resource
    LocalYml localYml;

    @Autowired
    StudentService studentService;
    private MultipartFile file;

    public ApiResponse uploadFile(MultipartFile file){
        //实例化json数据
        JSONObject jo = new JSONObject();
        if(file==null){
            throw new BusException("文件为空，上传失败！");
        }
        String fileName = System.currentTimeMillis()+file.getOriginalFilename();
        String filePath = localYml.getUploadAddress();

        try {
            uploadFile(file.getBytes(), filePath, fileName);
            jo.put("fileUrl", localYml.getVisitAddress()+fileName);
            jo.put("fileName", fileName);
        } catch (Exception e) {
            throw new BusException("文件上传失败");
        }
        //返回json
        return new ApiResponse(jo);
    }


    public ApiResponse uploadFile(MultipartFile file,String projectName){
        //实例化json数据
        JSONObject jo = new JSONObject();
        if(file==null){
            throw new BusException("文件为空，上传失败！");
        }
        String fileName = System.currentTimeMillis()+file.getOriginalFilename();
        String filePath = localYml.getUploadAddress2()+"/"+projectName;
        try {
            uploadFile(file.getBytes(), filePath, fileName);
            jo.put("fileUrl", localYml.getVisitAddress2()+"/"+projectName+"/"+fileName);
            jo.put("fileName", fileName);
            System.out.println("sucess");
        } catch (Exception e) {
            throw new BusException("文件上传失败");
        }
        //返回json
        return new ApiResponse(jo);
    }

    public ApiResponse uploadExcel(MultipartFile file,String schoolName,String uploadTime){
        //实例化json数据
        JSONObject jo = new JSONObject();
        if(file==null){
            throw new BusException("文件为空，上传失败！");
        }
        String fileName = file.getOriginalFilename();
//                                 /www/home/project
        String filePath = localYml.getUploadAddress2()+"/"+"do_one_do/excel";
        System.out.println("excel----》 fileName=="+fileName);
        System.out.println("excel----》 filePath=="+filePath);
        StuExecl one = stuExeclService.getOne(new LambdaQueryWrapper<StuExecl>().eq(StuExecl::getExcelName, fileName));
        if (one!=null){
            if (one.getExcelName().equals(fileName)&&one.getSchoolName().equals(schoolName)){
                throw new BusException("请勿重复上传");
            }
        }

//        String saveurl="/do_one_do/"+"excel/"+file.getOriginalFilename();
//        String dateStr = uploadTime+" 00:00:00";
//        String pattern = "yyyy-MM-dd HH:mm:ss";
//        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
//        StuExecl stuExecl = new StuExecl().setExcelName(fileName).setExcelUrl(saveurl).setSchoolName(schoolName);
//        stuExecl.setGmtCreate(LocalDateTime.parse(dateStr, dateTimeFormatter));
//        stuExeclService.save(stuExecl);
        try {
            uploadFile(file.getBytes(), filePath, fileName);
//                                                     /www/home/project/excel
//             visitAddress2: http://101.43.4.245:8080/upload           /excel
            jo.put("fileUrl", localYml.getVisitAddress2()+"/"+"excel"+"/"+fileName);
            jo.put("fileName", fileName);
            System.out.println("sucess");
        } catch (Exception e) {
            throw new BusException("文件上传失败");
        }
        //返回json
        return new ApiResponse(jo);
    }


//    public void uploadFile(MultipartFile file, String projectName, String stuId){
//        //实例化json数据
//        JSONObject jo = new JSONObject();
//        if(file==null){
//            throw new BusException("文件为空，上传失败！");
//        }
//        String fileName = System.currentTimeMillis()+file.getOriginalFilename();
//        String filePath = localYml.getUploadAddress2()+"/"+projectName;
//        try {
//            uploadFile(file.getBytes(), filePath, fileName);
//            jo.put("fileUrl", localYml.getVisitAddress2()+"/"+projectName+"/"+fileName);
//            jo.put("fileName", fileName);
//        } catch (Exception e) {
//            throw new BusException("文件上传失败");
//        }
//        Student one = studentService.getOne(new LambdaQueryWrapper<Student>().eq(Student::getStuId, stuId));
//        one.setImageUrl(jo.get("fileUrl").toString());
//        boolean b = studentService.updateById(one);
//        if(!b){
//            throw new BusException("存储图片url到数据库时出现异常");
//        }
//    }

    private static void uploadFile(byte[] file, String filePath, String fileName)throws Exception{
        File targetFile = new File(filePath);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath+"/"+fileName);
        System.out.println("fileoutpath============>"+filePath+"/"+fileName);
        out.write(file);
        out.flush();
        out.close();
    }
}
